package com.gjp.websockettest.config;

import com.gjp.websockettest.TestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;

@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {

    @Autowired
    private MyHandler myHandler;

    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry webSocketHandlerRegistry) {
        webSocketHandlerRegistry
                .addHandler(myHandler, "/myHandler")
                .setAllowedOrigins("*");
    }

    /**
     * text处理器
     */
    @Component
    class MyHandler extends TextWebSocketHandler {

        /**
         * 可以注入自己的业务逻辑对象
         */
        @Autowired
        private TestService testService;

        // 用来记录当前连接数的变量
        private volatile int onlineCount = 0;

        // concurrent包的线程安全Set，用来存放每个客户端对应的MyWebSocket对象
        private CopyOnWriteArraySet<WebSocketSession> users = new CopyOnWriteArraySet<>();

        /**
         * 连接成功时候，会触发UI上onopen方法
         */
        @Override
        public void afterConnectionEstablished(WebSocketSession session) throws IOException {
            System.out.println(session.getId() + " WebSocket 连接成功");
            users.add(session);
            onlineCount++;
            session.sendMessage(new TextMessage(session.getId() + "欢迎连接"));
        }

        /**
         * 在UI在用js调用websocket.send()时候，会调用该方法
         */
        @Override
        protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
            for (WebSocketSession user : users) {
                try {
                    if (user.isOpen()) {
                        String msg = session.getId() + " 数据：" + message.getPayload();
                        msg += " uuid=" +testService.test();
                        user.sendMessage(new TextMessage(msg));
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        @Override
        public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
            if (session.isOpen()) {
                session.close();
            }
            System.out.println(session.getId() + "WebSocket 断开连接 handleTransportError");
            users.remove(session);
            onlineCount--;
        }

        @Override
        public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
            System.out.println(session.getId() + "WebSocket 断开连接 afterConnectionClosed");
            users.remove(session);
        }

        @Override
        public boolean supportsPartialMessages() {
            return false;
        }

    }
}
